// Display type dropdown values
var DISPLAY_TYPE_VIEW_CURRENT_PROJECT = 1;
var DISPLAY_TYPE_VIEW_SYSTEM = 2;

var NOT_ASSIGNED_A_PROJECT = 0;

function createTableRowString(withTR, row) {
	var tableColumns = '<td class="action-column">\n'
	+ '<button class="edit-button">Edit</button>\n'
	+ '<button class="remove-button">Remove</button>\n'
	+ '</td>\n'
	+ '<td class="id-column">' + row.id	+ '</td>\n'
	+ '<td class="name-column">' + row.name	+ '</td>\n'
	+ '<td class="role-column">' + row.role_name + '</td>\n'
	+ '<td class="email-column">' + row.email + '</td>\n'
	+ '<td class="project-column">' + row.project_name + '</td>\n';
 
	if (withTR) {
		var tableRowString = '<tr id="' + row.id + '">\n'
			+ tableColumns
			+ '</tr>\n';
		
		return tableRowString;
	}
	
	return tableColumns;
}

function appendDataToTeamList(row) {
	$("#team-members tbody").append(createTableRowString(true, row));
	setTableView();
}

function insertDataInTeamList(insertBeforeThisRow, row) {
	$(insertBeforeThisRow).before(createTableRowString(true, row));
	setTableView();
}

function updateDataInTeamList(row) {
	var currentName = $("#" + row.id).find(".name-column").text();
	var currentProject = $("#" + row.id).find(".project-column").text();

	if ($("#display-type").val() == DISPLAY_TYPE_VIEW_CURRENT_PROJECT && currentProject != row.project_name) {
		$("#" + row.id).remove();
		return;
	}
	
	if (currentName == row.name) {
		$("#" + row.id).html(createTableRowString(false, row));
	}
	else {
		// if name change, delete old row and add new row
		$("#" + row.id).remove();
		insertRowSortedByName(row, 'team-members', insertDataInTeamList, appendDataToTeamList);
	}
	
	setTableView();
}

function validateTeamMemberData(source, all_team_member_fields, id, name, email, password, password2, role, project, team_member_tips) {
	var bValid = true;
	all_team_member_fields.removeClass("ui-state-error");
	bValid = bValid	&& checkLength(name, "name", 1, 50, team_member_tips);
	bValid = bValid	&& checkLength(email, "email", 1, 75, team_member_tips);
	bValid = bValid	&& checkEmail(source, id, email, "Email", team_member_tips);
	bValid = bValid	&& checkLength(password, "password", 8, 25, team_member_tips);
	bValid = bValid	&& checkLength(password2, "password", 8, 25, team_member_tips);
	bValid = bValid	&& checkMatchingPasswords(password, password2, team_member_tips);

	// 2 = Project Owner  TODO need GetRole(project_name) to get value from database
	if (role.val() == 2 && project.val() != NOT_ASSIGNED_A_PROJECT) {
		// if project already has a product owner, then error
		bValid = bValid && validateProductOwnerExists(id, role, project, team_member_tips);
	}

	return bValid;
}

function setTableView() {
	// hide or display project column based on View dropdown
	if ($("#display-type").val() == DISPLAY_TYPE_VIEW_CURRENT_PROJECT) {
		$(".project-column").hide();
	}
	else {
		$(".project-column").show();
	}

	// hide edit and remove buttons if normal user, except for edit button for this user
	if (sessionRoleName != "Product Owner") {
		$(".remove-button").hide();
		$("tr").not(':contains("' + sessionUserName + '")').find(".edit-button").hide();
	}
}

function loadTeamMemberTable() {
	var url = "GetTeamMembers";
	
	if ($("#display-type").val() == DISPLAY_TYPE_VIEW_SYSTEM) {
		url = "GetTeamMembers?system=true";
	}
	
	$.getJSON(url).done(function(result) {
		$("#team-members tbody").html("");			// clear table
	
		$.each(result.row, function(i, row) {
			appendDataToTeamList(row);
		});
	}).fail(function() {
		alert('Error loading data for team member table');
	});
}

function hideOrShowControls() {
	if (sessionRoleName == "Product Owner") {
		// if product owner is not assigned to a project
		if (sessionProjectId == 0) {
			$("#display-type").val(DISPLAY_TYPE_VIEW_SYSTEM);
			$("#display-type").hide();
		}
	}
	else {
		$("#add-team-member").hide();
		$("#display-type").hide();
	}
}		

// add team member dialog box script
$(function() {
	// add user story dialog box
    var name = $("#name" ),
      role = $("#role"),
      project = $("#project"),
      email = $("#email"),
      password = $("#password"),
      password2 = $("#password2"),
      all_team_member_fields = $([]).add(name).add(email).add(password).add(password2).add(role).add(project),
      team_member_tips = $(".teamValidateTips"),
      teamMemberValidateText = "All form fields are required.";

	function closeTeamMemberDialogBox(dialogBox) {
		all_team_member_fields.val("").removeClass("ui-state-error");
		all_team_member_fields.val("");
		$("#role")[0].selectedIndex = 0;
		$("#project")[0].selectedIndex = 0;
		$("p.teamValidateTips").text(teamMemberValidateText);
		$(dialogBox).dialog("close");
	}

    $("p.teamValidateTips").text(teamMemberValidateText);
    
	$("#team-dialog-form").dialog({
		autoOpen : false,
		height : 500,
		width : 550,
		modal : true
	});

	// populate roles dropdown from database
	$.getJSON("GetRoles").done(function(result) {
		$.each(result.row, function(i, row) {
			$("select[name='role']").append('<option value="' + row.id + '">' + row.name + '</option>\n');
		});
	})
	.fail(function() {
		alert('Error getting JSON for roles dropdown');
	});
	
	// populate projects dropdown from database
	$.getJSON("GetProjects").done(function(result) {
		$("select[name='project']").append('<option value="0">Not assigned to a project</option>\n');
		$.each(result.row, function(i, row) {
			$("select[name='project']").append('<option value="' + row.id + '">' + row.name + '</option>\n');
		});
	}).fail(function() {
		alert('Error getting JSON for projects dropdown');
	});

	hideOrShowControls();
	loadTeamMemberTable();
	
	// add callback for change with display type dropdown
	$("#display-type").change(function() {
		loadTeamMemberTable();
	});
	
	$("#add-team-member").button().click(function() {
		$("#team-dialog-form").dialog('option', 'title', 'Add new team member');
		$("#team-dialog-form").dialog({
			buttons : {
				"Add" : function() {
					if (validateTeamMemberData("ADD", all_team_member_fields, null, name, email, password, password2, role, project, team_member_tips)) {
						$.post("AddTeamMember", $("#team-member-form").serialize()).done(function(data) {
							var returnedData = jQuery.parseJSON(data);

							// if we are viewing the system or
							// the View is current project and returnedData.project_name are the same
							// then insert the row into the table
							
							if ($("#display-type").val() != DISPLAY_TYPE_VIEW_CURRENT_PROJECT
									|| sessionProjectId == returnedData.project_id) {

								insertRowSortedByName(returnedData, 'team-members', insertDataInTeamList, appendDataToTeamList);
							}
						}).fail(function(data) {
							alert("Failed to add new team member.");
						});
						$(this).dialog("close");
					}
				}
			},
			close : function() {
				closeTeamMemberDialogBox(this);
			}
		});
		$("#team-dialog-form").dialog("open");

	});
	
	$(document).on("click", ".edit-button", function() {
		var team_member_id=$(this).closest('tr').attr('id'); // get id from page
		var parameters = "teamMemberId=" + team_member_id;

		// get team member data from database by using id
		$.getJSON("GetTeamMemberData", parameters).done(function(returnedData) {
			$("#team-dialog-form").data('id', returnedData.id);
			$('#name').val(returnedData.name);
			$('#role').val(returnedData.role_id);
			$('#project').val(returnedData.project_id);
			$('#email').val(returnedData.email);
			$('#password').val(returnedData.password);
			$('#password2').val(returnedData.password);
		}).fail(function() {
			alert('Error getting team member data');
		});
		
		$("#team-dialog-form").dialog('option', 'title', 'Edit team member id ' + team_member_id);

		if (sessionRoleName == 'Team Member') {
			$('#name').attr("disabled", true); 
			$('#role').attr("disabled", true); 
			$('#project').attr("disabled", true);
		}
		
		$("#team-dialog-form").dialog({
			buttons : {
				"Update" : function() {
					if (validateTeamMemberData("EDIT", all_team_member_fields, team_member_id, name, email, password, password2, role, project, team_member_tips)) {
						id = $("#team-dialog-form").data('id');
						parameters = "team-member-id=" + id + "&" + $("#team-member-form").serialize();
						$.post("EditTeamMember", parameters).done(function(data) {
							var returnedData = jQuery.parseJSON(data);
							updateDataInTeamList(returnedData);
						}).fail(function(data) {
							alert("Failed to update team member.");
						});

						closeTeamMemberDialogBox(this);
					}
				}
			},
			close : function() {
				closeTeamMemberDialogBox(this);
			}
		});
		$("#team-dialog-form").dialog("open");
							
	});

	$(document).on("click", ".remove-button", function() {
		var team_member_id = $(this).closest('tr').attr('id');
		var team_member_name = $(this).closest('tr').find('.name-column').text();
		var confirmRemove = confirm('Are you sure you want to remove ' + team_member_name
				+ ' (id '+ team_member_id + ') from the system and clear any assigned tasks?');
		
		if (confirmRemove != true) return;
		
		var parameters = "team-member-id=" + team_member_id;
		
		$.post("RemoveTeamMember", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			if (returnedData.status == true) {
				$('#' + team_member_id).remove();
			}
			else {
				alert("Error removing " + team_member_name);
			}
		}).fail(function() {
			alert('Error completing removing a team member');
		});
	});
});
